package com.webserver.http;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class HttpServletRequest {
    private Socket socket;
    //请求行相关信息
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本

    private String requsetURI;
    private String queryString;

    private Map<String,String> parameters = new HashMap<>();

    //消息头相关信息
    private Map<String,String> headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException, EmptyRequsetException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析消息正文
        parseContent();
    }

    private void parseRequestLine() throws IOException, EmptyRequsetException {
        String line = readLine();

        if(line.isEmpty()){
            throw new EmptyRequsetException();
        }

        System.out.println(line);

        String[] array = line.split("\\s");
        method = array[0];
        uri = array[1];
        protocol = array[2];

        parseUri();

        System.out.println("method:"+method);         //GET
        System.out.println("uri:"+uri);               // /myweb/index.html
        System.out.println("protocol:"+protocol);     //HTTP/1.1
    }

    private void parseUri(){

        String[] arr = uri.split("\\?");
        requsetURI = arr[0];
        if(arr.length>1){
            queryString = arr[1];
            parseParameter(queryString);
        }

        System.out.println("requsetURI:"+requsetURI);
        System.out.println("queryString:"+queryString);
        System.out.println("parameters:"+parameters);
    }

    private void parseHeaders() throws IOException {
        while (true) {
            String line = readLine();
            if(line.isEmpty()){
                break;
            }
            System.out.println("消息头:"+line);

            String[] key_value = line.split(":\\s");
            headers.put(key_value[0].toLowerCase(),key_value[1]);
        }
        System.out.println("headers:"+headers);
    }

    private void parseContent() throws IOException {
        if("post".equalsIgnoreCase(method)){
            if(headers.containsKey("content-length")){
                int contentLength = Integer.parseInt(headers.get("content-length"));
                System.out.println("------"+contentLength+"------");

                byte[] data = new byte[contentLength];
                InputStream in = socket.getInputStream();
                in.read(data);

                if(headers.containsKey("content-type")){
                    String contentType = headers.get("content-type");
                    System.out.println("------"+contentType+"------");

                    if("application/x-www-form-urlencoded".equals(contentType)){
                        String line = new String(data, StandardCharsets.ISO_8859_1);
                        System.out.println("正文内容:"+line);
                        parseParameter(line);
                    }

                }
            }

        }

    }

    private void parseParameter(String line){
        try {
            line = URLDecoder.decode(line,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] data = line.split("&");
        for(String s : data){
            String[] key_value = s.split("=");
            parameters.put(key_value[0],key_value.length>1?key_value[1]:null);
        }
    }

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();

        char pre = 'a', cur = 'a';//pre上次读取的字符，cur本次读取的字符
        StringBuilder builder = new StringBuilder();
        int d;
        while ((d = in.read())!=-1) {
            cur = (char)d;
            if(pre == 13 && cur == 10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name.toLowerCase());
    }

    public String getRequsetURI() {
        return requsetURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getParameter(String name){
        return parameters.get(name);
    }

    public Map<String,String> getParameters(){
        return new HashMap(parameters);//复制一个Map返回，保证封装性
    }
}
